package cn.echo.sharding.config;

import cn.echo.sharding.aspectj.HintMasterRouteAspect;
import cn.echo.sharding.database.DefaultDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * 数据源抽象类型
 * @author lonyee
 */
public abstract class AbstractDatabaseConfigSupport {

    protected static final Logger log = LoggerFactory.getLogger(AbstractDatabaseConfigSupport.class);

    @Bean(name="defaultDataSource")
    @ConfigurationProperties(prefix = "sharding.jdbc")
    public DefaultDataSource defaultDataSource() {
        return new DefaultDataSource();
    }

    /** sharding-jdbc数据源配置 */
    @Primary
    @Bean(name="dataSource")
    @ConditionalOnBean(name = "defaultDataSource")
    public abstract DataSource dataSource(@Qualifier("defaultDataSource") DefaultDataSource defaultDataSource) throws SQLException;


    @Bean
    public PlatformTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        PlatformTransactionManager platformTransactionManager = new DataSourceTransactionManager(dataSource);
        return platformTransactionManager;
    }

    @Bean
    public HintMasterRouteAspect hintMasterRouteAspect() {
        return new HintMasterRouteAspect();
    }
}
